package com.commerce.product.consumer;

import com.commerce.common.constant.RabbitMQConstant;
import com.commerce.common.message.FlashSaleMessage;
import com.commerce.product.service.FlashSaleOrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 秒杀订单消息消费者
 */
@Slf4j
@Component
public class FlashSaleOrderConsumer {

    @Autowired
    private FlashSaleOrderService flashSaleOrderService;

    /**
     * 处理秒杀订单创建消息
     */
    @RabbitListener(queues = RabbitMQConstant.FLASH_SALE_ORDER_QUEUE, 
                   containerFactory = "flashSaleRabbitListenerContainerFactory")
    public void handleFlashSaleOrder(FlashSaleMessage message, Message mqMessage, Channel channel) {
        long deliveryTag = mqMessage.getMessageProperties().getDeliveryTag();
        
        try {
            log.info("收到秒杀订单消息: messageId={}, userId={}, productId={}", 
                    message.getMessageId(), message.getUserId(), message.getProductId());

            // 处理秒杀订单
            boolean success = flashSaleOrderService.processFlashSaleOrder(message);
            
            if (success) {
                // 处理成功，手动确认消息
                channel.basicAck(deliveryTag, false);
                log.info("秒杀订单处理成功: messageId={}, orderNo={}", 
                        message.getMessageId(), message.getOrderNo());
            } else {
                // 处理失败，检查重试次数
                message.incrementRetryCount();
                
                if (message.isMaxRetryExceeded()) {
                    // 超过最大重试次数，拒绝消息并不重新入队
                    channel.basicNack(deliveryTag, false, false);
                    log.error("秒杀订单处理失败，超过最大重试次数: messageId={}, retryCount={}", 
                             message.getMessageId(), message.getRetryCount());
                    
                    // 发送到死信队列或记录失败日志
                    flashSaleOrderService.handleFailedOrder(message);
                } else {
                    // 拒绝消息并重新入队
                    channel.basicNack(deliveryTag, false, true);
                    log.warn("秒杀订单处理失败，将重试: messageId={}, retryCount={}", 
                            message.getMessageId(), message.getRetryCount());
                }
            }
            
        } catch (Exception e) {
            log.error("处理秒杀订单消息异常: messageId={}, error={}", 
                     message.getMessageId(), e.getMessage(), e);
            
            try {
                // 异常情况下拒绝消息并重新入队
                channel.basicNack(deliveryTag, false, true);
            } catch (IOException ioException) {
                log.error("消息确认失败: {}", ioException.getMessage());
            }
        }
    }

    /**
     * 处理库存回滚消息
     */
    @RabbitListener(queues = RabbitMQConstant.FLASH_SALE_STOCK_ROLLBACK_QUEUE,
                   containerFactory = "flashSaleRabbitListenerContainerFactory")
    public void handleStockRollback(FlashSaleMessage message, Message mqMessage, Channel channel) {
        long deliveryTag = mqMessage.getMessageProperties().getDeliveryTag();
        
        try {
            log.info("收到库存回滚消息: messageId={}, userId={}, productId={}", 
                    message.getMessageId(), message.getUserId(), message.getProductId());

            // 处理库存回滚
            boolean success = flashSaleOrderService.rollbackStock(message);
            
            if (success) {
                channel.basicAck(deliveryTag, false);
                log.info("库存回滚成功: messageId={}", message.getMessageId());
            } else {
                channel.basicNack(deliveryTag, false, true);
                log.warn("库存回滚失败，将重试: messageId={}", message.getMessageId());
            }
            
        } catch (Exception e) {
            log.error("处理库存回滚消息异常: messageId={}, error={}", 
                     message.getMessageId(), e.getMessage(), e);
            
            try {
                channel.basicNack(deliveryTag, false, true);
            } catch (IOException ioException) {
                log.error("消息确认失败: {}", ioException.getMessage());
            }
        }
    }

    /**
     * 处理订单超时消息（死信队列）
     */
    @RabbitListener(queues = RabbitMQConstant.FLASH_SALE_ORDER_DLQ,
                   containerFactory = "flashSaleRabbitListenerContainerFactory")
    public void handleOrderTimeout(FlashSaleMessage message, Message mqMessage, Channel channel) {
        long deliveryTag = mqMessage.getMessageProperties().getDeliveryTag();
        
        try {
            log.info("收到订单超时消息: messageId={}, userId={}, productId={}", 
                    message.getMessageId(), message.getUserId(), message.getProductId());

            // 处理订单超时
            boolean success = flashSaleOrderService.handleOrderTimeout(message);
            
            if (success) {
                channel.basicAck(deliveryTag, false);
                log.info("订单超时处理成功: messageId={}", message.getMessageId());
            } else {
                channel.basicNack(deliveryTag, false, false); // 不重新入队
                log.error("订单超时处理失败: messageId={}", message.getMessageId());
            }
            
        } catch (Exception e) {
            log.error("处理订单超时消息异常: messageId={}, error={}", 
                     message.getMessageId(), e.getMessage(), e);
            
            try {
                channel.basicAck(deliveryTag, false); // 确认消息，避免重复处理
            } catch (IOException ioException) {
                log.error("消息确认失败: {}", ioException.getMessage());
            }
        }
    }
}
